package com.estore.network;

import com.estore.service.ProductService;
import com.estore.service.UserService;
import com.estore.model.Product;
import com.estore.model.User;

import java.io.*;
import java.net.*;
import java.util.List;
import java.util.Set;

/**
 * 商城服务器端
 */


public class EStoreServer {
    private ProductService productService;
    private UserService userService;
    private ServerSocket serverSocket;
    private static final int PORT = 8888;

    public EStoreServer() {
        this.productService = new ProductService();
        this.userService = new UserService();
    }

    public void start() {
        try {
            serverSocket = new ServerSocket(PORT);
            System.out.println("服务器已启动，监听端口: " + PORT);
            System.out.println("等待客户端连接...");

            while (true) {
                Socket clientSocket = serverSocket.accept();
                System.out.println("接收到客户端连接: " + clientSocket.getInetAddress());

                // 为每个客户端连接创建新线程处理
                new Thread(() -> handleClient(clientSocket)).start();
            }
        } catch (IOException e) {
            System.err.println("服务器启动失败: " + e.getMessage());
        } finally {
            if (serverSocket != null && !serverSocket.isClosed()) {
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    System.err.println("关闭服务器失败: " + e.getMessage());
                }
            }
        }
    }

    private void handleClient(Socket clientSocket) {
        try (ObjectInputStream ois = new ObjectInputStream(clientSocket.getInputStream());
             ObjectOutputStream oos = new ObjectOutputStream(clientSocket.getOutputStream())) {

            // 读取客户端请求类型
            String requestType = (String) ois.readObject();
            System.out.println("接收到客户端请求类型: " + requestType);

            // 处理不同类型的请求
            Object response = processRequest(requestType, ois);

            // 发送响应
            oos.writeObject(response);
            oos.flush();
            System.out.println("已发送响应给客户端");

        } catch (IOException | ClassNotFoundException e) {
            System.err.println("处理客户端请求时发生错误: " + e.getMessage());
        } finally {
            try {
                clientSocket.close();
            } catch (IOException e) {
                System.err.println("关闭客户端连接失败: " + e.getMessage());
            }
        }
    }

    private Object processRequest(String requestType, ObjectInputStream ois) throws IOException, ClassNotFoundException {
        switch (requestType) {
            case "LOGIN":
                String username = (String) ois.readObject();
                String password = (String) ois.readObject();
                User user = userService.login(username, password);
                System.out.println("用户登录尝试: " + username + (user != null ? " 成功" : " 失败"));
                return user;

            case "REGISTER":
                String newUsername = (String) ois.readObject();
                String newPassword = (String) ois.readObject();
                boolean registerResult = userService.register(newUsername, newPassword);
                System.out.println("用户注册: " + newUsername + (registerResult ? " 成功" : " 失败"));
                return registerResult;

            case "GET_ALL_PRODUCTS":
                List<Product> products = productService.getAllProducts();
                System.out.println("返回商品列表，共 " + products.size() + " 个商品");
                return products;

            case "ADD_PRODUCT":
                User addProductUser = (User) ois.readObject();
                if (!userService.hasAdminPermission(addProductUser)) {
                    return "ERROR: 权限不足，只有管理员可以添加商品";
                }
                Product newProduct = (Product) ois.readObject();
                boolean addResult = productService.addProduct(newProduct);
                if (addResult) {
                    System.out.println("管理员添加商品: " + newProduct.getName());
                    return "SUCCESS: 商品添加成功: " + newProduct.getName();
                } else {
                    return "ERROR: 商品ID已存在，添加失败";
                }

            case "UPDATE_PRODUCT":
                User updateProductUser = (User) ois.readObject();
                if (!userService.hasAdminPermission(updateProductUser)) {
                    return "ERROR: 权限不足，只有管理员可以更新商品";
                }
                Product updatedProduct = (Product) ois.readObject();
                boolean updateResult = productService.updateProduct(updatedProduct);
                if (updateResult) {
                    System.out.println("管理员更新商品: " + updatedProduct.getName());
                    return "SUCCESS: 商品更新成功: " + updatedProduct.getName();
                } else {
                    return "ERROR: 商品不存在，更新失败";
                }

            case "DELETE_PRODUCT":
                User deleteProductUser = (User) ois.readObject();
                if (!userService.hasAdminPermission(deleteProductUser)) {
                    return "ERROR: 权限不足，只有管理员可以删除商品";
                }
                String deleteProductId = (String) ois.readObject();
                boolean deleteResult = productService.deleteProduct(deleteProductId);
                if (deleteResult) {
                    System.out.println("管理员删除商品: " + deleteProductId);
                    return "SUCCESS: 商品删除成功";
                } else {
                    return "ERROR: 商品不存在，删除失败";
                }

            case "ADJUST_STOCK":
                User adjustStockUser = (User) ois.readObject();
                if (!userService.hasAdminPermission(adjustStockUser)) {
                    return "ERROR: 权限不足，只有管理员可以调整库存";
                }
                String adjustProductId = (String) ois.readObject();
                int adjustQuantity = (Integer) ois.readObject();
                boolean adjustResult = productService.adjustStock(adjustProductId, adjustQuantity);
                if (adjustResult) {
                    System.out.println("管理员调整库存: 商品ID=" + adjustProductId + ", 数量=" + adjustQuantity);
                    return "SUCCESS: 库存调整成功";
                } else {
                    return "ERROR: 库存调整失败，商品不存在或库存不足";
                }

            case "PURCHASE_PRODUCT":
                String purchaseProductId = (String) ois.readObject();
                int purchaseQuantity = (Integer) ois.readObject();
                boolean purchaseResult = productService.purchaseProduct(purchaseProductId, purchaseQuantity);
                if (purchaseResult) {
                    System.out.println("用户购买商品: 商品ID=" + purchaseProductId + ", 数量=" + purchaseQuantity);
                    return "SUCCESS: 购买成功";
                } else {
                    return "ERROR: 购买失败，商品不存在或库存不足";
                }

            case "ADD_TAG":
                User addTagUser = (User) ois.readObject();
                if (!userService.hasAdminPermission(addTagUser)) {
                    return "ERROR: 权限不足，只有管理员可以管理标签";
                }
                String addTagProductId = (String) ois.readObject();
                String newTag = (String) ois.readObject();
                boolean addTagResult = productService.addTagToProduct(addTagProductId, newTag);
                if (addTagResult) {
                    System.out.println("管理员添加标签: 商品ID=" + addTagProductId + ", 标签=" + newTag);
                    return "SUCCESS: 标签添加成功";
                } else {
                    return "ERROR: 标签添加失败，商品不存在";
                }

            case "REMOVE_TAG":
                User removeTagUser = (User) ois.readObject();
                if (!userService.hasAdminPermission(removeTagUser)) {
                    return "ERROR: 权限不足，只有管理员可以管理标签";
                }
                String removeTagProductId = (String) ois.readObject();
                String removeTag = (String) ois.readObject();
                boolean removeTagResult = productService.removeTagFromProduct(removeTagProductId, removeTag);
                if (removeTagResult) {
                    System.out.println("管理员移除标签: 商品ID=" + removeTagProductId + ", 标签=" + removeTag);
                    return "SUCCESS: 标签移除成功";
                } else {
                    return "ERROR: 标签移除失败，商品不存在或标签不存在";
                }

            case "GET_PRODUCT_TAGS":
                String tagsProductId = (String) ois.readObject();
                Set<String> tags = productService.getProductTags(tagsProductId);
                return tags;

            case "BACKUP_DATA":
                User backupUser = (User) ois.readObject();
                if (!userService.hasAdminPermission(backupUser)) {
                    return "ERROR: 权限不足，只有管理员可以备份数据";
                }
                try {
                    productService.backupData();
                    System.out.println("管理员执行数据备份");
                    return "SUCCESS: 数据备份成功";
                } catch (IOException e) {
                    return "ERROR: 备份失败 - " + e.getMessage();
                }

            default:
                return "ERROR: 未知请求类型: " + requestType;
        }
    }

    public static void main(String[] args) {
        EStoreServer server = new EStoreServer();
        server.start();
    }
}